package com.monitor.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * HTTP客户端工具类，用于处理网络请求
 */
public class HttpClient {
    private static final int CONNECT_TIMEOUT = 5000; // 连接超时时间，单位毫秒
    private static final int READ_TIMEOUT = 5000;   // 读取超时时间，单位毫秒
    
    /**
     * 发送POST请求
     * 
     * @param apiUrl 请求URL
     * @param jsonData JSON格式的请求数据
     * @return 服务器响应内容
     * @throws IOException 如果发生网络错误
     */
    public static String post(String apiUrl, String jsonData) throws IOException {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        try {
            // 设置请求属性
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            
            // 写入请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            
            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    return response.toString();
                }
            } else {
                // 处理错误响应
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    throw new IOException("HTTP错误代码: " + responseCode + ", 响应: " + errorResponse.toString());
                }
            }
        } finally {
            connection.disconnect();
        }
    }
    
    /**
     * 发送GET请求
     * 
     * @param apiUrl 请求URL
     * @param params 请求参数
     * @return 服务器响应内容
     * @throws IOException 如果发生网络错误
     */
    public static String get(String apiUrl, Map<String, String> params) throws IOException {
        // 构建带参数的URL
        StringBuilder urlBuilder = new StringBuilder(apiUrl);
        if (params != null && !params.isEmpty()) {
            urlBuilder.append('?');
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.append(entry.getKey())
                          .append('=')
                          .append(entry.getValue())
                          .append('&');
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1); // 删除最后一个&
        }
        
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        try {
            // 设置请求属性
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setRequestProperty("Accept", "application/json");
            
            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    return response.toString();
                }
            } else {
                // 处理错误响应
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    throw new IOException("HTTP错误代码: " + responseCode + ", 响应: " + errorResponse.toString());
                }
            }
        } finally {
            connection.disconnect();
        }
    }
}